<template>
  <view class="container">
    <FilterNavbar :searchList="searchList" v-model:queryParam="queryParam" @confirm="() => getListAndStatistics(false)">
      <template #center>
        <view class="navbar-title"> 车辆违章 </view>
      </template>
    </FilterNavbar>
    <view class="page-filter">
      <!-- 关键字搜索 -->
      <ve-search-bar placeholder="请输入车牌号/承租人/交车人" v-model="queryParam.keyword" @search="handleSearch"></ve-search-bar>
      <ve-tabs :actived="activedTab" :list="tabs" @change="tabsChange"></ve-tabs>
      <!-- 标签 -->
      <view class="tags-box">
        <StatusTags v-model="queryParam.handlePayStatus" :list="tags" @change="tagsChange" />
      </view>
    </view>
    <!-- 列表 -->
    <!-- @scroll="onScroll" -->
    <scroll-view
      scroll-y
      :scroll-top="scrollTop"
      :scroll-with-animation="true"
      refresher-enabled
      :refresher-triggered="refreshStatus"
      :enable-back-to-top="true"
      @refresherrefresh="getListAndStatistics(true)"
      @scrolltolower="reachBottom"
    >
      <view class="record-list">
        <OrderItem v-for="record in dataSource" :record="record" :key="record.id" />
        <!-- 加载结束列表为空时展示 -->
        <ve-empty v-if="dataSource.length == 0 && loadStatus == 'nomore'"></ve-empty>
        <!-- 底部加载状态 -->
        <ve-load-more v-else :status="loadStatus" bgColor="#F7F7F9"></ve-load-more>
      </view>
    </scroll-view>
    <ve-bottom-box v-if="usePermission('svmsapp:car-violation.add')">
      <ve-button type="primary" @click="add" size="long">新增车辆违章</ve-button>
    </ve-bottom-box>
  </view>
</template>

<script setup>
  import { ref, onMounted, computed } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import FilterNavbar from '@/components/FilterNavbar'
  import { usePageDict, useSysDict } from '@/hooks/useDict'
  import useList from '@/hooks/useList'
  import { usePermission } from '@/hooks/usePermission'
  import { getViolationStatusCount, getViolationHandleCount } from '@/api/asset/car-violation'
  import OrderItem from './components/orderItem.vue'
  import StatusTags from './components/status-tags.vue'

  const dict = usePageDict('carViolationDict')
  const sysDict = useSysDict(['short_order_channel_type'])

  const searchList = computed(() => {
    return [
      // {
      //   prop: 'violationCodeLike',
      //   label: '违章单号',
      //   type: 'input',
      // },
      {
        prop: 'carSiteIdList',
        label: '车辆当前归属门店',
        type: 'remote-select',
        attrs: {
          type: 'site',
          multiple: true,
          params: {
            idList: queryParam.value.carSiteIdList,
          },
        },
      },
      {
        prop: 'siteIdList',
        label: '违章单关联门店',
        type: 'remote-select',
        attrs: {
          type: 'site',
          multiple: true,
          params: {
            idList: queryParam.value.siteIdList,
          },
        },
      },
      {
        prop: ['eventTimeStart', 'eventTimeEnd'],
        label: '违章周期',
        type: 'daterange-picker',
        attrs: {
          mode: 'date',
          valueFormat: 'YYYY-MM-DD',
        },
      },
      {
        prop: 'urgePayStatus',
        label: '催缴状态',
        type: 'picker',
        attrs: {
          options: dict.urgePayStatus,
        },
      },
      {
        prop: 'handleType',
        label: '处理方',
        type: 'picker',
        attrs: {
          options: dict.violationHandleEnum,
        },
      },
      {
        prop: 'staffIdList',
        label: '负责人',
        type: 'remote-select',
        attrs: {
          type: 'staff_all_bysite',
          multiple: true,
          params: {
            idList: queryParam.value.staffIdList,
          },
        },
      },
      {
        prop: 'violationFeeStateList',
        label: '费用状态',
        type: 'remote-select',
        attrs: {
          type: 'dict',
          title: '选择费用状态',
          multiple: true, // 多选
          outData: dict.violationFeeStateEnum,
        },
      },
      {
        prop: 'violationParty',
        label: '违章发生方',
        type: 'picker',
        attrs: {
          options: dict.violationPartyEnum,
        },
      },
      {
        prop: 'violationLabel',
        label: '违章标签',
        type: 'picker',
        attrs: {
          options: dict.violationLabelEnum
            ? dict.violationLabelEnum.map((it) => {
                return {
                  label: it.label,
                  value: it.label,
                }
              })
            : [],
        },
      },
      {
        prop: 'violationChargeTypeList',
        label: '违章押金收取方式',
        type: 'remote-select',
        attrs: {
          title: '选择违章押金收取方式',
          type: 'dict',
          multiple: true, // 多选
          outData: dict.inExpWayList,
        },
      },
      {
        prop: 'violationCodeLike',
        label: '违章单号',
        type: 'input',
      },
      {
        prop: 'channelType',
        label: '订单渠道',
        type: 'picker',
        attrs: {
          options: sysDict.short_order_channel_type,
        },
      },
    ]
  })

  const queryParam = ref({})
  const { resetRefresh, reachBottom, loadData, scrollTop, loadStatus, refreshStatus, dataSource } = useList(
    '/V5/violation/getList',
    queryParam,
  )

  const add = () => {
    uni.navigateTo({
      url: '/pages/asset/car-violation/components/add',
    })
  }

  const activedTab = ref(0)
  const tabs = ref([
    { label: '全部', value: undefined, num: 0 },
    { label: '未处理', value: 0, num: 0 },
    { label: '已处理', value: 1, num: 0 },
    { label: '已关闭', value: 3, num: 0 },
  ])
  const tags = ref([
    { name: '超过7天未处理', num: 0, value: 4 },
    { name: '未处理未收款', num: 0, value: 0 },
    { name: '已处理未收款', num: 0, value: 1 },
    { name: '超过15天未处理', num: 0, value: 5 },
    { name: '不配合处理', num: 0, value: 3 },
    { name: '未处理已收款', num: 0, value: 2 },
  ])

  // 状态change
  const tabsChange = (e, tab) => {
    activedTab.value = e
    queryParam.value.eventStatus = tab.value
    // 清空tags
    queryParam.value.handlePayStatus = undefined
    getListAndStatistics()
  }

  // 标签change
  const tagsChange = (val) => {
    // 状态切到全部
    queryParam.value.eventStatus = undefined
    activedTab.value = 0
    queryParam.value.handlePayStatus = val
    getListAndStatistics()
  }

  const handleSearch = () => {
    getListAndStatistics(false)
  }

  const getListAndStatistics = (pullDown = false) => {
    const params = {
      siteIdList: queryParam.value.siteIdList,
      eventTimeStart: queryParam.value.eventTimeStart,
      eventTimeEnd: queryParam.value.eventTimeEnd,
      urgePayStatus: queryParam.value.urgePayStatus,
      handleType: queryParam.value.handleType,
      staffIdList: queryParam.value.staffIdList,
      violationFeeStateList: queryParam.value.violationFeeStateList,
      violationParty: queryParam.value.violationParty,
      violationLabel: queryParam.value.violationLabel,
      violationChargeTypeList: queryParam.value.violationChargeTypeList,
      violationCodeLike: queryParam.value.violationCodeLike,
    }
    // 获取状态统计
    getViolationStatusCount(params).then((res) => {
      if (res.code == 200) {
        const result = res.result
        tabs.value[0].num = result.all
        tabs.value[1].num = result.notDeal
        tabs.value[2].num = result.dealed
        tabs.value[3].num = result.close
      }
    })
    getViolationHandleCount(params).then((res) => {
      if (res.code == 200) {
        const result = res.result
        tags.value[0].num = result.exceed7Day
        tags.value[1].num = result.noHandleNoPay
        tags.value[2].num = result.onHandleNoPay
        tags.value[3].num = result.exceed15Day
        tags.value[4].num = result.lesseeNoJoin
        tags.value[5].num = result.noHandleOnPay
      }
    })
    if (pullDown) {
      resetRefresh(true)
    } else {
      loadData(1)
    }
  }

  // 控制tags展示 begin
  const showTags = ref(true)
  let lastScrollTop,
    nowScrollTop = 0
  let isListening = false
  const onScroll = (e) => {
    nowScrollTop = e.detail.scrollTop
    if (isListening) return
    lastScrollTop = e.detail.scrollTop
    isListening = true
    setTimeout(() => {
      if (lastScrollTop > nowScrollTop || nowScrollTop < 40) {
        showTags.value = true
      } else {
        showTags.value = false
      }
      isListening = false
    }, 200)
  }
  // end

  onLoad((data) => {
    // 接收参数（
    if (data.eventStatus == 0) {
      console.log(data)
      queryParam.value.eventStatus = 0
      queryParam.value.siteIdList = data.siteId ? [Number(data.siteId)] : undefined
      queryParam.value.keyword = data.keyword
      searchList.value[0].attrs.label = data.siteName ? data.siteName : undefined
      activedTab.value = 1
    }
    // 获取数据、统计
    getListAndStatistics()
    // 监听刷新
    uni.$on('refreshData', () => {
      getListAndStatistics()
    })
  })
</script>

<style lang="less" scoped>
  .container {
    height: 100vh;
  }
  .record-list {
    padding: 24rpx;
  }
  .tags-box {
    width: 100%;
    background: #fff;
    padding: 12px 24rpx 24rpx;
    // position: fixed;
    // top: 292rpx;
    // z-index: 3;
  }
  .page-filter {
    background: #fff;
  }
  :deep(.ve-cell-title) {
    width: 220rpx;
    max-width: 220rpx;
  }
</style>
